package com.nlx.notes.support.helper.redis;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nlx.notes.module.core.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RedisHelper {


    final RedisTemplate<String, Object> redisTemplate;

    public RedisHelper(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 通过key 获取信息
     * @param key key
     * @return V
     */
    public <T> T getKey(String key, Class<T> clazz) {
        if (log.isDebugEnabled()) {
            log.debug("find redis key -> {}", key);
        }

        if (StrUtil.isEmpty(key)) {
            return null;
        }

        Object rawValue = redisTemplate.opsForValue().get(key);
        if (rawValue == null) {
            return null;
        }

        if (clazz.isInstance(rawValue)) {
            return clazz.cast(rawValue);
        }

        try {
//            log.info("reids value :{}" ,rawValue);
            // 若 Redis 中存储的是 JSON 字符串，则转换
            String json = rawValue.toString();
            T value = JSONUtils.parse(json, clazz);
            if (log.isDebugEnabled()) {
                log.debug("redis key result -> {}", json);
            }
            return value;
        } catch (Exception e) {
            log.error("Failed to convert redis value to target type: {}", clazz.getName(), e);
            return null;
        }
    }

    /**
     * 保存数据
     * @param key key
     * @param value value
     */
    public void setValue(String key, Object value, long timeout, TimeUnit unit){
        if(log.isDebugEnabled()){
            log.debug(" set redis data,key- > {} ,value ->{},timeout ->{},unit ->{}",key,value,timeout,unit.toString());
        }
        if(value instanceof String){
            redisTemplate.opsForValue().set(key,value,timeout,unit);
        }else{
            redisTemplate.opsForValue().set(key,JSONUtils.toString(value),timeout,unit);
        }
    }


    public boolean removeKey(String key) {
        if(log.isDebugEnabled()){
            log.debug("remove key ,key- -> {}",key);
        }
       return  redisTemplate.delete(key);
    }

    public void ttlKey(String key, long ttl, TimeUnit unit) {
        redisTemplate.expire(key,ttl,unit);
    }
}
